package com.app.couponsharelife.ui.main.me.feedback

import android.content.Intent
import android.text.TextUtils
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.bilibili.boxing.Boxing
import com.bilibili.boxing.model.config.BoxingConfig
import com.bilibili.boxing.model.entity.impl.ImageMedia
import com.bilibili.boxing.utils.ImageCompressor
import com.bilibili.boxing_impl.ui.BoxingActivity
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.FeedbackPicsListAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.viewmodel.MeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_feedback.*
import kotlinx.android.synthetic.main.common_tool_bar_layout.*

class FeedbackActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_feedback

    private val REQUEST_CODE = 101

    private var mViewModel: MeViewModel? = null

    private var selectPosition = -1

    override fun initViews() {
        AppUtils.initImmersionBar(this,false)
        initToolBar()
        initRecyclerView()
        tvUploadProblem.setOnClickListener {
            uploadMultiPics()
        }
    }

    private fun initToolBar() {
        ivBack.setOnClickListener { finish() }
        tvToolBarTitle.text = "问题反馈"
    }

    private fun initRecyclerView() {
        mRecyclerView.layoutManager = object : androidx.recyclerview.widget.GridLayoutManager(this, 3) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        mRecyclerView.adapter = FeedbackPicsListAdapter(arrayListOf(""), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                selectPosition = arg1
                val videoConfig = BoxingConfig(BoxingConfig.Mode.SINGLE_IMG).needCamera(R.drawable.camera_white_icon)
                Boxing.of(videoConfig).withIntent(this@FeedbackActivity, BoxingActivity::class.java).start(this@FeedbackActivity, REQUEST_CODE)
            }
        })
    }

    private fun uploadMultiPics() {
        if (TextUtils.isEmpty(etFeedbackContent.text)) {
            showToastMsg("请输入问题内容")
            return
        }
        if ((mRecyclerView.adapter as FeedbackPicsListAdapter).list.isEmpty()) {
            addFeedback("")
        } else {
            val sb = StringBuilder()
            for (item in (mRecyclerView.adapter as FeedbackPicsListAdapter).list) {
                if (item != "") {
                    sb.append(item)
                    sb.append(",")
                }
            }
            if (sb.toString() != "") {
                val map = HashMap<String, String>()
                map["files"] = sb.toString()
                mViewModel?.freshUploadMultiPics(map, true)
            } else {
                addFeedback("")
            }
        }
    }

    private fun addFeedback(imgs: String) {
        if (TextUtils.isEmpty(etFeedbackContent.text)) {
            showToastMsg("请输入问题内容")
            return
        }
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["content"] = etFeedbackContent.text.toString().trim()
        if (imgs != "" && imgs != "[]")
            map["imgs"] = imgs
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshAddFeedback(map, true)
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(MeViewModel::class.java)
        if (!mViewModel!!.uploadMultiPics()!!.hasObservers()) {
            mViewModel!!.uploadMultiPics()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUploadMultiPics(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshUploadMultiPics(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshUploadMultiPics(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            addFeedback(it.data.data.toString())
                        } else {
                            dismissProgressDialog()
                            showToastMsg("提交失败")
                        }
                    }
                }
            })
            mViewModel!!.addFeedback()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshAddFeedback(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshAddFeedback(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshAddFeedback(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            showToastMsg("提交成功")
                            finish()
                        } else {
                            showToastMsg("提交失败")
                        }
                    }
                }
            })
        }
    }

    //头像选择回调
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 0) {
            return
        }
        if (data == null) {
            return
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE) {
                val medias = Boxing.getResult(data)
                if (medias != null) {
                    (medias[0] as ImageMedia).compress(ImageCompressor(this))
                    if ((medias[0] as ImageMedia).compressPath != null) {
                        (mRecyclerView.adapter as FeedbackPicsListAdapter).addData((medias[0] as ImageMedia).compressPath, selectPosition)
                    } else {
                        showToastMsg("图片选择失败，请重新选择")
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}
